package deptlogic

import (
	"context"

	"go-zero-admin/apps/system/cmd/rpc/internal/svc"
	"go-zero-admin/apps/system/cmd/rpc/syspb"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetDeptSonByPidLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetDeptSonByPidLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetDeptSonByPidLogic {
	return &GetDeptSonByPidLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetDeptSonByPidLogic) GetDeptSonByPid(in *syspb.GetDeptSonByPidReq) (*syspb.GetDeptSonByPidResp, error) {
	if len(in.GetList()) == 0 {
		return &syspb.GetDeptSonByPidResp{List: nil}, nil
	}

	// 处理数据
	var children []*syspb.SysDept
	for _, v := range in.GetList() {
		if v.GetParentId() != in.GetPid() {
			continue
		}

		children = append(children, v)

		// 递归查询
		resp, e := l.GetDeptSonByPid(&syspb.GetDeptSonByPidReq{
			Pid:  v.GetDeptId(),
			List: in.GetList(),
		})
		if e != nil {
			return nil, e
		}

		if len(resp.GetList()) == 0 {
			continue
		}

		children = append(children, resp.GetList()...)
	}

	return &syspb.GetDeptSonByPidResp{List: children}, nil
}
